import { fetchDemandList } from '../../../utils/request';

Page({
  page: {
    size: 5,
    num: 1,
  },

  data: {
    orderList: [],
    listLoading: 0,
    pullDownRefreshing: false,
    backRefresh: false,
    status: 1,
  },

  handleEdit(e) {
    const essayId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/usercenter/match-list/index?demandId=' + essayId,
    })
  },

  onLoad() {
    // this.refreshList();
    this.pullDownRefresh = this.selectComponent('#wr-pull-down-refresh');
  },

  onShow() {
    this.onRefresh();
  },

  onReachBottom() {
    if (this.data.listLoading === 0) {
      this.getData(this.data.curTab);
    }
  },

  onPageScroll(e) {
    this.pullDownRefresh && this.pullDownRefresh.onPageScroll(e);
  },

  onPullDownRefresh_(e) {
    const { callback } = e.detail;
    this.setData({ pullDownRefreshing: true });
    this.refreshList(this.data.curTab)
      .then(() => {
        this.setData({ pullDownRefreshing: false });
        callback && callback();
      })
      .catch((err) => {
        this.setData({ pullDownRefreshing: false });
        Promise.reject(err);
      });
  },

  getData(reset = false) {
    const params = {
      parameter: {
        pageSize: this.page.size,
        pageNum: this.page.num,
        self: true
      },
    };
    this.setData({ listLoading: 1 });
    return fetchDemandList(params.parameter)
      .then((res) => {
        this.page.num++;
        let orderList = [];
        if (res && res.data && res.data.content) {
          orderList = res.data.content;
        }
        return new Promise((resolve) => {
          if (reset) {
            this.setData({ orderList: [] }, () => resolve());
          } else resolve();
        }).then(() => {
          this.setData({
            orderList: this.data.orderList.concat(orderList),
            listLoading: orderList.length > 0 ? 0 : 2,
          });
        });
      })
      .catch((err) => {
        this.setData({ listLoading: 3 });
        return Promise.reject(err);
      });
  },

  onReTryLoad() {
    this.getData();
  },

  onTabChange(e) {
    const { value } = e.detail;
    this.setData({
      status: value,
    });
    this.refreshList(value);
  },

  refreshList() {
    this.page = {
      size: this.page.size,
      num: 1,
    };
    this.setData({ orderList: [] });

    return Promise.all([
      this.getData(true),
    ]);
  },

  onRefresh() {
    this.refreshList();
  },

  onOrderCardTap(e) {
    console.log("onOrderCardTap", e);
    const { order } = e.currentTarget.dataset;
    const id = order.id;
    wx.navigateTo({
      url: `/pages/essay-detail/essay-detail?essayId=${id}`,
    });
  },
});
